import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class RecommendedPopularityController extends GetxController {
  RxInt type = 0.obs;
  RxBool isPai = false.obs;

  List<String> topList = [
    'https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000318/100016911994/FocusFullshop/CkRqZnMvdDEvMTc4MjE3LzI1LzEzMjAzLzIwMjc1Mi82MGU2OTNjNUUyZThjNjcwYS8xNmRlYzMwY2IxYzhhZmNkLnBuZxIJMy10eV8wXzU0MAI4vot6QhkKFeW-l-WKm-iHquihjOi9pumFjeS7thABQg0KCei0rei_h-eYvhACQhAKDOeri-WNs-aKoui0rRAGQgoKBuWKm-iNkBAHWPrs48v0Ag/cr/s/q.jpg',
    'https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000366/10070551792932/FocusFullshop/CkJqZnMvdDEvMjM2NTM0LzcvMTY1OTcvNTA5MjkvNjY0YmE4YjVGMjVkNjc5ZDYvZmJmZTFjYTk5NDVhOTYxNS5wbmcSCTMtdHlfMF81NDACOO6LekITCg_msYnlrqLooYzmnY7nrrEQAUIQCgzmu6EyOTnlh48xMDAQAkIQCgznq4vljbPmiqLotK0QBkIKCgbnsr7pgIkQB1ikmqbdi6UC/cr/s/q.jpg',
    'https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000367/100089763932/FocusFullshop/CkNqZnMvdDEvMjM3MTU0LzEzLzE2NjYzLzU5MTQ5LzY2NDhmZWVlRjQyMmQ2MDg4LzcxM2VlYWNhMTBhOWFhMTQucG5nEgk0LXR5XzBfNTUwAjjvi3pCFQoRVGhpbmtQYWTnrJTorrDmnKwQAUIWChLnsr7lvankuI3lrrnplJnov4cQAkIQCgznq4vljbPmiqLotK0QBkIKCgbnsr7pgIkQB1jcsMLu9AI/cr/s/q.jpg',
    'https://imgcps.jd.com/ling-cubic/ling4/lab/amZzL3QxLzIwNjA3MC8xMC8zMDU5MS80MjkzMS82M2YzMTkxNEY5NjAyMmNjNy83ODExODJhZWM4ZGFmZjNiLnBuZw/5Lqs6YCJ5aW96LSn/5L2g5YC85b6X5oul5pyJ/1635188467440111618/cr/s/q.jpg',
    'https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000368/100085422930/FocusFullshop/CkNqZnMvdDEvMjA4MDc5LzM0LzQyNjM5LzYxNDAwLzY2NTYxNzliRjQ2MmY0YTk2L2E3YzY3M2Q3NGNmZTFmNWEuanBnEgo5OTktdHlfMF8xMAE48It6WNK2uez0Ag/cr/s/q.jpg',
    'https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000322/7728113/FocusFullshop/CkJqZnMvdDEvMTA0NDUyLzIvMzA5NTcvNjM4NDgvNjNlYzhlMjhGMDUxYmVmMTIvZTVjY2Q0YzIwYjY0NDFhMi5qcGcSCTItdHlfMF81MzABOMKLekIcChjpm6rkvZvpvpnmsb3ovablhbvmiqTlk4EQAUITCg_kvJjmg6DkuqvkuI3lgZwQAkIQCgznq4vljbPmiqLotK0QBkIKCgbkvJjpgIkQB1jx19cD/cr/s/q.jpg',
  ];
}

class RecommendedPopularityPage extends GetView<RecommendedPopularityController> {
  const RecommendedPopularityPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: Text(
          '人气推荐',
          style: StylesUtils.customTextStyle(
              fontSize: StylesUtils.fontSize18, fontWeight: FontWeight.w600),
        ),
        actions: [
          IconButton(onPressed: () {}, icon: SvgUtils.assetName('u3577', width: 20, height: 20)),
          IconButton(onPressed: () {}, icon: SvgUtils.assetName('u3578', width: 20, height: 20))
        ],
      ),
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: SizedBox(
              height: 125,
              child: Swiper.children(
                  autoplay: true,
                  duration: 500,
                  autoplayDelay: 5000,
                  pagination: SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                          activeColor: Colors.white,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.color6666),
                          size: 10.w,
                          activeSize: 10.w),
                      alignment: Alignment.bottomCenter),
                  children: controller.topList
                      .map((e) => CachedNetworkImage(
                            imageUrl: e,
                            width: double.infinity,
                            height: 125,
                            fit: BoxFit.fill,
                          ))
                      .toList()),
            ),
          ),
          SliverPersistentHeader(
            delegate: _MyHeaderDelegate(
                child: Container(
              height: 40,
              color: Colors.white,
              child: Row(
                children: [
                  Expanded(
                      child: Center(
                          child: InkWell(
                    onTap: () {
                      controller.type.value = 1;
                      controller.isPai.value = false;
                    },
                    child: Obx(
                      () => Text.rich(TextSpan(children: [
                        TextSpan(
                            text: '综合排序',
                            style: StylesUtils.customTextStyle(
                                color: controller.type.value == 1
                                    ? ColorsUtils.colorF048
                                    : ColorsUtils.color6666)),
                      ])),
                    ),
                  ))),
                  Expanded(
                      child: Center(
                    child: InkWell(
                      onTap: () {
                        controller.isPai.value = false;
                        if (controller.type.value == 2) {
                          controller.type.value = 3;
                          return;
                        }
                        if (controller.type.value == 2) {
                          controller.type.value = 3;
                          return;
                        }
                        controller.type.value = 2;
                      },
                      child: Obx(() => Text.rich(TextSpan(
                              text: '价格排序',
                              style: StylesUtils.customTextStyle(
                                  color: [2, 3].contains(controller.type.value)
                                      ? ColorsUtils.colorF048
                                      : ColorsUtils.color6666),
                              children: [
                                WidgetSpan(
                                    child: SizedBox(
                                      width: 10,
                                      height: 16,
                                      child: Column(
                                        children: [
                                          CustomPaint(
                                            size: const Size(10, 6),
                                            painter:
                                                _MyCustomPainter(controller.type.value == 2, true),
                                          ),
                                          Container(
                                            height: 4,
                                          ),
                                          CustomPaint(
                                            size: const Size(10, 6),
                                            painter: _MyCustomPainter(controller.type.value == 3),
                                          ),
                                        ],
                                      ),
                                    ),
                                    alignment: PlaceholderAlignment.middle)
                              ]))),
                    ),
                  )),
                  Expanded(
                      child: Container(
                    alignment: Alignment.centerRight,
                    padding: EdgeInsets.only(right: 15.w),
                    child: Obx(() => IconButton(
                        onPressed: () {
                          controller.isPai.value = !controller.isPai.value;
                          controller.type.value = 0;
                        },
                        icon: RichText(
                          text: TextSpan(children: [
                            TextSpan(
                                text: '人气排序 ',
                                style: StylesUtils.customTextStyle(
                                    color: controller.isPai.isTrue
                                        ? ColorsUtils.colorF048
                                        : ColorsUtils.color6666)),
                            WidgetSpan(
                                child: SvgUtils.assetName(
                                    controller.isPai.isTrue ? 'u3761_selected' : 'u3761',
                                    width: 18,
                                    height: 10),
                                alignment: PlaceholderAlignment.middle)
                          ]),
                        ))),
                  ))
                ],
              ),
            )),
            pinned: true,
          ),
          SliverPadding(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            sliver: SliverToBoxAdapter(
              child: StaggeredGrid.count(
                crossAxisCount: 2,
                crossAxisSpacing: 15,
                mainAxisSpacing: 20,
                children: [
                  for (var i = 0; i < 45; i++)
                    Column(
                      children: [
                        CachedNetworkImage(
                          imageUrl:
                              'https://img10.360buyimg.com/mobilecms/s230x230_jfs/t1/223657/28/31706/59671/664344c3Fafdbc368/20c3aaf6378cb7c1.jpg!cc_230x230!q70.dpg.webp',
                          height: 116,
                          width: double.infinity,
                          fit: BoxFit.fill,
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 5.h),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '办公桌简易桌子卧室台式',
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 15.h, bottom: 10.h),
                          alignment: Alignment.centerLeft,
                          child: RichText(
                            text: TextSpan(children: [
                              TextSpan(
                                text: '￥1299.00',
                                style: StylesUtils.customTextStyle(color: ColorsUtils.colorF048),
                              ),
                              TextSpan(
                                  text: '      人气值 38',
                                  style: StylesUtils.customTextStyle(color: ColorsUtils.color9999))
                            ]),
                          ),
                        ),
                      ],
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _MyHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double height;

  final Widget child;

  _MyHeaderDelegate({required this.child, this.height = 40.0});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return maxExtent != oldDelegate.maxExtent && minExtent != oldDelegate.minExtent;
  }
}

class _MyCustomPainter extends CustomPainter {
  final bool result;
  final bool isUp;

  _MyCustomPainter(this.result, [this.isUp = false]);

  @override
  void paint(Canvas canvas, Size size) {
    Path path = Path();
    if (isUp) {
      path.moveTo(0, size.height);
      path.lineTo(size.width, size.height);
      path.lineTo(size.width / 2, size.height / 2);
    } else {
      path.moveTo(0, 0);
      path.lineTo(size.width, 0);
      path.lineTo(size.width / 2, size.height / 2);
    }
    path.close();
    Paint paint = Paint()
      ..style = PaintingStyle.fill
      ..strokeCap = StrokeCap.square
      ..color = ColorsUtils.parseColorFromHexString(ColorsUtils.color6666);
    if (result) {
      paint.color = ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048);
    }
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}
